var express = require('express');
var router = express.Router();
var Manager = require('../modules/mongo')
var Token = require('../modules/token')
var ObjectId = require('mongodb').ObjectID;

var DBManager =new Manager()

router.get('/',function(req, res, next){
    let req_data = req.query
    let params ={
        userName: req_data.userName,
        password: req_data.password
    }
    DBManager.findOne('users', params, result => {
        if(result.success){
            let obj ={
                _id: result.result._id,
                userName: result.result.userName
            }
            let token = Token.createToken(obj)
            res.send({success:true, code:0,message:'登录成功',data:result.result,token: token})
        }else{
            res.send({success:false,code:1,message:'登录失败',data:[]});
        }
    })
})

router.get('/loginUserInfo',function(req, res, next){
    let req_data = req.headers
    let _token =req_data['x-token']
    let obj = Token.decodeToken(_token)
    DBManager.findOne('users', {_id: ObjectId(obj.payload.data._id)}, result => {
        if(result.success){
            res.send({success:true, message:'用户信息', result:result.result})
            return
        }
        res.send({success:false, code:1, message:'Token不存在'});
    })
    
   
})

module.exports = router;